import { useLocation } from "react-router-dom";
import { Link } from "react-router-dom";
import { Breadcrumb as AntdBreadcrumb } from "antd";
import { getPathTitle, ROUTE_PATHS } from "@/constants/common";

type BreadcrumbItem = {
  title: React.ReactNode;
};

export default function Breadcrumb() {
  const location = useLocation();

  // 基于当前路径构建面包屑
  const buildBreadcrumbItems = () => {
    const pathSegments = location.pathname.split("/").filter(Boolean);
    const items: BreadcrumbItem[] = [];

    let currentPath = "";

    pathSegments.forEach((segment, index) => {
      currentPath += `/${segment}`;

      // 使用工具函数获取路径标题
      const title = getPathTitle(currentPath);

      if (title) {
        // 如果是最后一个路径段，不添加链接
        if (index === pathSegments.length - 1) {
          items.push({
            title: <span>{title}</span>,
          });
        } else {
          // 对于动态路由，需要构建正确的链接路径
          let linkPath = currentPath;
          if (currentPath.includes("/detail/")) {
            // 如果是详情页，链接应该指向列表页
            linkPath = ROUTE_PATHS.order;
          }
          items.push({
            title: <Link to={linkPath}>{title}</Link>,
          });
        }
      }
    });

    return items;
  };

  return <AntdBreadcrumb items={buildBreadcrumbItems()} />;
}
